﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using Ecommerce.Models;
using Library;
using Library.Models;
using Library.MVCHelpers;
using Newtonsoft.Json;

namespace Ecommerce.Controllers
{
    public class SharedController : BaseController
    {
        public ActionResult Breadcrumb(BreadcrumbViewModel[] breadcrumb)
        {
            if (breadcrumb == null)
                return null;
            return PartialView(breadcrumb);
        }

        public ActionResult Menu(int menuGroupId, string activeUrl)
        {
            var menus = DatabaseConnector.Menus.Where(m => m.MenuGroupId == menuGroupId && m.Culture == CurrentCulture).OrderBy(m => m.DisplayOrder);

            var model = new Dictionary<Menu, List<Menu>>();
            foreach (var menu in menus)
            {
                if (menu.ParentId.HasValue)
                {
                    var parentMenu = menus.FirstOrDefault(m => m.Id == menu.ParentId);
                    if (parentMenu != null)
                    {
                        List<Menu> tempList;
                        if (model.TryGetValue(parentMenu, out tempList))
                        {
                            tempList.Add(menu);
                        }
                        else
                        {
                            model.Add(parentMenu, new List<Menu> { menu });
                        }
                    }
                }
                else
                {
                    model.Add(menu, new List<Menu>());
                }
            }

            ViewBag.ActiveUrl = activeUrl;
            return PartialView(model);
        }

        [HttpGet]
        public ActionResult ConfirmDialog(string title, string content, string alertTitle)
        {
            ViewBag.Title = title;
            ViewBag.Content = content;
            ViewBag.AlertTitle = alertTitle;
            return PartialView();
        }

        #region Contact form
        [HttpGet]
        [Compress]
        public ActionResult Contact()
        {
            return PartialView(new ContactViewModel(new Contact()));
        }

        [HttpPost]
        public async Task<ActionResult> Contact(ContactViewModel model)
        {
            if (ModelState.IsValid)
            {
                using(var db = DatabaseConnector)
                {
                    db.Contacts.Add(new Contact()
                    {
                        SenderName = model.SenderName,
                        SenderEmail = model.SenderEmail,
                        Content = model.Content
                    });

                    var result = await db.SaveChangesAsync();
                    if (result > 0)
                    {
                        ViewBag.Thankyou = NOWCulture.GetString("Thank you for contacting us. An email has been sent to the relevant department and somebody will be in contact with you shortly.");
                        return PartialView(model);
                    }
                }
            }
            return PartialView(model);
        }
        #endregion

        #region Image browser

        [HttpGet]
        [Compress]
        public string ImageBrowser(string imageDirectoryUrl)
        {
            var directory = Server.MapPath("~" + imageDirectoryUrl);
            if (Directory.Exists(directory))
            {
                var directoryInfo = new DirectoryInfo(directory);
                var fileInfoList = directoryInfo.GetFiles();
                if (fileInfoList.Length > 0)
                {
                    var list = fileInfoList.Select(fileInfo => new SimpleImage()
                    {
                        Url = imageDirectoryUrl + "/" + fileInfo.Name
                    }).ToList();
                    return JsonConvert.SerializeObject(list, Formatting.None, new ViewHelper.NOWJsonSerializerSettings());
                }
            }

            return JsonConvert.SerializeObject(new List<SimpleImage>(), Formatting.None, new ViewHelper.NOWJsonSerializerSettings());;
        }

        private class SimpleImage
        {
            public string Url { get; set; }
        }

        [HttpPost]
        [Compress]
        [Authorize(Roles = "Administrators, Editors, Image Editors, Page Editors, Product Editors")]
        public async Task<JsonResult> UploadImages(string imageDirectoryUrl)
        {
            var resultList = new List<string>();
            try
            {
                foreach (string file in Request.Files)
                {
                    var fileContent = Request.Files[file];
                    if (fileContent != null && fileContent.ContentLength > 0)
                    {
                        if (!Settings.ValidImageTypes.Contains(fileContent.ContentType))
                        {
                            return new ViewHelper.HttpStatusCodeJsonResult(HttpStatusCode.InternalServerError, NOWCulture.GetString("Please choose either a GIF, JPG or PNG image."));
                        }

                        // get a stream
                        var stream = fileContent.InputStream;

                        // and optionally write the file to disk
                        var fileName = Path.GetFileName(fileContent.FileName);
                        if (fileName != null)
                        {
                            var directoryPath = Server.MapPath("~" + imageDirectoryUrl);
                            if (!Directory.Exists(directoryPath))
                            {
                                Directory.CreateDirectory(directoryPath);
                            }

                            var imagePath = Path.Combine(directoryPath, fileName);
                            using (var fileStream = System.IO.File.Create(imagePath))
                            {
                                await stream.CopyToAsync(fileStream);
                            }
                            resultList.Add(imageDirectoryUrl + "/" + fileName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex);
                return new ViewHelper.HttpStatusCodeJsonResult(HttpStatusCode.InternalServerError, NOWCulture.GetString("There are system errors, please contact with developers to handle."));
            }

            return new ViewHelper.HttpStatusCodeJsonResult(HttpStatusCode.OK, resultList);
        }
        #endregion
    }
}